<template>
  <div class="skuProperty">
    <el-tree ref="vuetree" class="tree-wrapper" node-key="id" :data="treeData" :props="defaultProps" highlight-current @node-click="handleNodeClick" :expand-on-click-node="false" default-expand-all>
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span class="name">{{ node.label }}</span>
        <span v-if="!data.attrKeyList" class="btn-wrapper">
          <i class="el-icon-delete" @click.stop="deleteTreeNode(node,data)"></i>
          <i class="el-icon-edit" @click.stop="editTreeNode(node,data)"></i>
          <i class="el-icon-circle-plus-outline" @click.stop="addTreeNode(node,data)"></i>
        </span>
      </span>
    </el-tree>
    <div class="wrapper">
      <div class="header">
        <h3>{{title.primaryTitle}} / {{title.subTitle}}</h3>
        <el-button type="primary" size="small" @click="showPropertyDialog">新增属性</el-button>
      </div>
      <ul class="list">
        <li class="list-item" v-for="(item,index) in propertyData" :key="index">
          <span>{{item.name}}</span>
          <i class="el-icon-circle-plus-outline" @click="addDialog(item)"></i>
          <i class="el-icon-edit" @click="editDialog(item)"></i>
          <i class="el-icon-delete" @click="deleteDialog(item.id,index)"></i>
        </li>
      </ul>
    </div>
    <el-dialog title="新增属性" width="25%" :visible.sync="addProperty.show">
      <ul class="dialog-list">
        <li class="dialog-item">
          <span>名称：</span>
          <el-input size="small" v-model="addProperty.name" placeholder="请输入名称"></el-input>
        </li>
      </ul>
      <div slot="footer">
        <el-button type="primary" @click="addPropertySubmit" size="medium">保存</el-button>
        <el-button @click="addProperty.show = false" size="medium">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="属性值" width="25%" :visible.sync="addData.show">
      <ul class="dialog-list">
        <li class="dialog-item">
          <span>属性：</span> {{addData.name}}
        </li>
        <li class="dialog-item">
          <span>属性值：</span>
          <div class="val-list">
            <div class="add-input" v-for="(item,index) in addData.list" :key="item.id">
              <el-input type="text" size="small" v-model="item.value"></el-input>
              <i class="el-icon-remove" @click="removeVal(1,index)"></i>
            </div>
            <div class="add-input" v-for="(item,index) in addData.inputList" :key="'1'+index" v-if="addData.inputList.length">
              <el-input type="text" size="small" v-model="item.value"></el-input>
              <i class="el-icon-remove" @click="removeVal(2,index)"></i>
            </div>
            <i class="add-icon el-icon-circle-plus" @click="addVal"></i>
          </div>
        </li>
      </ul>
      <div slot="footer">
        <el-button type="primary" @click="addSubmit" size="medium">保存</el-button>
        <el-button @click="addData.show = false" size="medium">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑属性" width="25%" :visible.sync="editData.show">
      <ul class="dialog-list">
        <li class="dialog-item">
          <span>名称：</span>
          <el-input size="small" v-model="editData.name" placeholder="请输入名称"></el-input>
        </li>
      </ul>
      <div slot="footer">
        <el-button type="primary" @click="editSubmit" size="medium">保存</el-button>
        <el-button @click="editData.show = false" size="medium">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog title="系统提示" width="25%" :visible="false">
      <div>删除后不可恢复！您确定要删除吗?</div>
      <div slot="footer">
        <el-button type="primary" @click="editSubmit">保存</el-button>
        <el-button @click="editData.show = false">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="treeEdit.type===1?'新增二级分类':'编辑二级分类'" width="25%" :visible.sync="treeEdit.show">
      <el-input size="small" v-model.trim="treeEdit.name" placeholder="请输入名称"></el-input>
      <div slot="footer">
        <el-button type="primary" @click="treeEditSubmit">保存</el-button>
        <el-button @click="treeEdit.show = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      treeEdit: {
        type: null,
        show: false,
        name: '',
        node: null,
        treeData: null
      },
      addData: {
        show: false,
        id: null,
        name: "",
        list: [],
        inputList: []
      },
      editData: {
        show: false,
        name: "",
        id: null
      },
      addProperty: {
        show: false,
        pId: null,
        name: ""
      },
      defaultProps: {
        children: "attrKeyList",
        label: "name"
      },
      treeData: [],
      title: {
        primaryTitle: "",
        subTitle: ""
      },
      propertyData: []
    };
  },
  mounted() {
    this.getTreeData();
  },
  methods: {
    deleteTreeNode(node, treeData) {
      const parent = node.parent;
      const children = parent.data.attrKeyList || parent.data;
      const index = children.findIndex(d => d.id === treeData.id);
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$post({
          api: '/delete/attrkey',
          data: {
            id: treeData.id
          }
        }).then(({ data }) => {
          if (data.code === 0) {
            children.splice(index, 1);
            if (this.$refs.vuetree.getCurrentKey() == treeData.id) {
              this.getPropertyData(
                this.treeData[0].attrKeyList[0].id,
                this.treeData[0].name,
                this.treeData[0].attrKeyList[0].name
              );
              setTimeout(() => {
                this.$refs.vuetree.setCurrentKey(this.treeData[0].attrKeyList[0].id);
              });
            }
          } else {
            this.$message({
              message: data.msg,
              type: "error"
            });
          }
        })
      }).catch(() => {

      });
    },
    addTreeNode(node, treeData) {
      this.treeEdit = {
        type: 1,
        show: true,
        node,
        treeData,
        name: ''
      }
    },
    editTreeNode(node, treeData) {
      this.treeEdit = {
        type: 2,
        show: true,
        node,
        treeData,
        name: treeData.name
      }
    },
    async treeEditSubmit() {
      let link = '', params = {};
      params.name = this.treeEdit.name;
      if (!params.name) {
         this.$message.error('请输入名称');
         return;
      }
      if (this.treeEdit.type === 1) {
        link = '/add/attrkey';
        params.pId = this.treeEdit.treeData.pid;
      } else {
        link = '/update/attrkey';
        params.id = this.treeEdit.treeData.id;
      }

      let { data } = await this.$post({
        api: link,
        data: params
      })
      if (data.code === 0) {
        if (this.treeEdit.type === 1) {
          const parent = this.treeEdit.node.parent.data;
          parent.attrKeyList.push(data.data)
        } else {
          this.treeEdit.treeData.name = this.treeEdit.name;
        }
        this.treeEdit.show = false;
      } else {
        this.$message({
          message: data.msg,
          type: "error"
        });
      }
      console.log(params)
    },
    async getTreeData() {
      let { data } = await this.$post({
        api: "/show/leftmenu"
      });
      this.treeData = data.data;
      this.getPropertyData(
        this.treeData[0].attrKeyList[0].id,
        this.treeData[0].name,
        this.treeData[0].attrKeyList[0].name
      );
      setTimeout(() => {
        this.$refs.vuetree.setCurrentKey(this.treeData[0].attrKeyList[0].id);
      });
    },
    async getPropertyData(id, primaryTitle, subTitle) {
      let { data } = await this.$post({
        api: "/show/propertyInfo",
        data: {
          id: id
        }
      });
      this.title = {
        primaryTitle: primaryTitle,
        subTitle: subTitle
      };
      this.addProperty.pId = id;
      this.propertyData = data.data.attrKeyList;
    },
    handleNodeClick(data, node) {
      if (!data.attrKeyList) {
        this.getPropertyData(data.id, node.parent.data.name, data.name);
      }
    },
    showPropertyDialog() {
      this.addProperty.show = true;
      this.addProperty.name = "";
    },
    async addPropertySubmit() {
      if (!this.addProperty.name) {
        this.$message({
          message: "名称不能为空！",
          type: "error"
        });
      } else {
        let { data } = await this.$post({
          api: "/add/attrkey",
          data: this.addProperty
        });
        if (data.code === 0) {
          this.getPropertyData(
            this.addProperty.pId,
            this.title.primaryTitle,
            this.title.subTitle
          );
          this.addProperty.show = false;
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      }
    },
    addDialog(item) {
      this.addData = {
        show: true,
        id: item.id,
        name: item.name,
        list: item.attrValueList.concat(),
        inputList: []
      };
    },
    removeVal(type, index) {
      if (type == 1) {
        this.addData.list.splice(index, 1);
      } else {
        this.addData.inputList.splice(index, 1);
      }
    },
    addVal() {
      if (this.addData.inputList.length + this.addData.list.length < 10) {
        this.addData.inputList.push({ value: "" });
      } else {
        this.$message({
          type: "error",
          message: "属性值不超过10个"
        });
      }
    },
    addSubmit() {
      let arr = this.addData.inputList.concat(this.addData.list);
      for (let i = 0; i < arr.length; i++) {
        if (!arr[i].value) {
          this.$message({
            type: "error",
            message: "属性值不能为空"
          });
          return;
        }
        for (let k = 0; k < arr.length; k++) {
          if (arr[i].value == arr[k].value && i != k) {
            this.$message({
              type: "error",
              message: "属性值不能重复"
            });
            return false;
          }
        }
      }
      let params = { key: this.addData.id, valueIds: "", valueNames: "" };
      if (this.addData.list.length) {
        let arr = [];
        this.addData.list.forEach((item, index) => {
          arr.push(item.id + '=' + item.value);
        });
        params.valueIds = arr.join(",");
      }
      if (this.addData.inputList.length) {
        let arr = [];
        this.addData.inputList.forEach((item, index) => {
          arr.push(item.value);
        });
        params.valueNames = arr.join(",");
      }
      this.$post({
        api: "/add/attrvalue",
        data: params
      }).then(({ data }) => {
        if (data.code === 0) {
          this.getPropertyData(
            this.addProperty.pId,
            this.title.primaryTitle,
            this.title.subTitle
          );
          this.addData.show = false;
        } else {
          this.$message({
            type: "error",
            message: data.msg
          });
        }
      });
    },
    editDialog(item) {
      this.editData.show = true;
      this.editData.name = item.name;
      this.editData.id = item.id;
    },
    async editSubmit() {
      let { data } = await this.$post({
        api: "/update/attrkey",
        data: this.editData
      });
      if (data.code === 0) {
        this.getPropertyData(
          this.addProperty.pId,
          this.title.primaryTitle,
          this.title.subTitle
        );
        this.editData.show = false;
      } else {
        this.$message({
          type: "error",
          message: data.msg
        });
      }
    },
    deleteDialog(id, index) {
      this.$confirm("删除后不可恢复！您确定要删除吗?", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$post({
          api: "/delete/attrkey",
          data: {
            id: id
          }
        }).then(({ data }) => {
          if (data.code === 0) {
            this.propertyData.splice(index, 1);
            this.$message({
              type: "success",
              message: data.msg
            });
          } else {
            this.$message({
              type: "error",
              message: data.msg
            });
          }
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  .name {
    flex: 1;
    padding: 6px 0;
  }
  i:nth-child(2) {
    margin: 0 5px;
  }
}
.skuProperty {
  display: flex;
  min-height: calc(100vh - 104px);
}

.tree-wrapper {
  flex: 0 0 200px;
  width: 200px;
  padding: 15px 0;
  border-right: 1px solid #eeeeee;
}

.wrapper {
  flex: 1;
  .header {
    overflow: hidden;
    padding: 15px 30px;
    border-bottom: 1px solid #eeeeee;
  }
  h3 {
    float: left;
    width: 200px;
    line-height: 32px;
    font-size: 16px;
  }
  .el-button {
    float: left;
  }
  .list {
    overflow: hidden;
    padding: 30px;
    &-item {
      float: left;
      width: 20%;
      line-height: 50px;
      i {
        font-size: 16px;
        margin: 0 5px;
        cursor: pointer;
      }
    }
  }
}

.dialog-list {
  .dialog-item {
    display: flex;
    margin-bottom: 30px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  span {
    width: 0 0 80px;
    flex: 0 0 80px;
    vertical-align: middle;
  }
  .el-radio {
    margin-top: 5px;
  }
  .val-list span:not(:last-child) {
    position: relative;
    display: inline-block;
    width: 100px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    margin: 0 6px 15px 0;
    border: 1px solid #ccc;
    cursor: pointer;
    i {
      position: absolute;
      right: -4px;
      top: -6px;
      color: red;
    }
  }
  .add-icon {
    color: #409eff;
    font-size: 26px;
    cursor: pointer;
  }
  .add-input {
    position: relative;
    display: inline-block;
    width: 100px;
    height: 30px;
    vertical-align: top;
    margin: 0 6px 15px 0;
    i {
      position: absolute;
      right: -4px;
      top: -6px;
      color: red;
      background: #fff;
    }
  }
}
</style>